import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as path;
import 'path_util.dart';

/// 图片备份工具类，用于处理图片文件的复制和打包
class ImageBackupUtil {
  /// 复制图片文件到备份目录
  /// 
  /// [imagePath] 图片的原始路径
  /// [backupDir] 备份目录
  /// 返回复制后的相对路径
  static Future<String> copyImageToBackupDir(String? imagePath, String backupDir) async {
    // 如果路径为空，直接返回空字符串
    if (imagePath == null || imagePath.isEmpty) {
      return '';
    }
    
    // 如果是网络URL，直接返回
    if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
      return imagePath;
    }
    
    try {
      // 检查文件是否存在
      final file = File(imagePath);
      if (!await file.exists()) {
        print('图片文件不存在: $imagePath');
        return '';
      }
      
      // 创建图片备份目录
      final imageBackupDir = Directory('$backupDir/images');
      if (!await imageBackupDir.exists()) {
        await imageBackupDir.create(recursive: true);
      }
      
      // 获取文件名
      final fileName = path.basename(imagePath);
      
      // 设置目标路径
      final targetPath = '${imageBackupDir.path}/$fileName';
      
      // 复制文件
      await file.copy(targetPath);
      
      // 返回相对路径
      return 'images/$fileName';
    } catch (e) {
      print('复制图片文件时出错: $e');
      return '';
    }
  }
  
  /// 从备份目录复制图片文件到应用目录
  /// 
  /// [relativePath] 图片的相对路径
  /// [backupDir] 备份目录
  /// [appDir] 应用目录
  /// 返回复制后的绝对路径
  static Future<String> copyImageFromBackupDir(String? relativePath, String backupDir, String appDir) async {
    // 如果路径为空，直接返回空字符串
    if (relativePath == null || relativePath.isEmpty) {
      return '';
    }
    
    // 如果是网络URL，直接返回
    if (relativePath.startsWith('http://') || relativePath.startsWith('https://')) {
      return relativePath;
    }
    
    try {
      // 获取备份目录中的图片路径
      final backupImagePath = '$backupDir/$relativePath';
      
      // 检查文件是否存在
      final backupFile = File(backupImagePath);
      if (!await backupFile.exists()) {
        print('备份图片文件不存在: $backupImagePath');
        return '';
      }
      
      // 创建应用图片目录
      final appImageDir = Directory('$appDir/images');
      if (!await appImageDir.exists()) {
        await appImageDir.create(recursive: true);
      }
      
      // 获取文件名
      final fileName = path.basename(relativePath);
      
      // 设置目标路径
      final targetPath = '${appImageDir.path}/$fileName';
      
      // 复制文件
      await backupFile.copy(targetPath);
      
      // 返回绝对路径
      return targetPath;
    } catch (e) {
      print('从备份目录复制图片文件时出错: $e');
      return '';
    }
  }
  
  /// 处理数据中的所有图片，复制到备份目录
  /// 
  /// [questions] 题目列表
  /// [notes] 笔记列表
  /// [essayMaterials] 作文素材列表
  /// [backupDir] 备份目录
  static Future<void> processAndCopyAllImages(List<dynamic> questions, List<dynamic> notes, List<dynamic> essayMaterials, String backupDir) async {
    // 处理题目图片
    for (var question in questions) {
      // 复制题目图片
      if (question.questionImageUrl != null && question.questionImageUrl.isNotEmpty) {
        final relativePath = await copyImageToBackupDir(question.questionImageUrl, backupDir);
        if (relativePath.isNotEmpty) {
          question.questionImageUrl = relativePath;
        }
      }
      
      // 复制选项A图片
      if (question.optionAImageUrl != null && question.optionAImageUrl.isNotEmpty) {
        final relativePath = await copyImageToBackupDir(question.optionAImageUrl, backupDir);
        if (relativePath.isNotEmpty) {
          question.optionAImageUrl = relativePath;
        }
      }
      
      // 复制选项B图片
      if (question.optionBImageUrl != null && question.optionBImageUrl.isNotEmpty) {
        final relativePath = await copyImageToBackupDir(question.optionBImageUrl, backupDir);
        if (relativePath.isNotEmpty) {
          question.optionBImageUrl = relativePath;
        }
      }
      
      // 复制选项C图片
      if (question.optionCImageUrl != null && question.optionCImageUrl.isNotEmpty) {
        final relativePath = await copyImageToBackupDir(question.optionCImageUrl, backupDir);
        if (relativePath.isNotEmpty) {
          question.optionCImageUrl = relativePath;
        }
      }
      
      // 复制选项D图片
      if (question.optionDImageUrl != null && question.optionDImageUrl.isNotEmpty) {
        final relativePath = await copyImageToBackupDir(question.optionDImageUrl, backupDir);
        if (relativePath.isNotEmpty) {
          question.optionDImageUrl = relativePath;
        }
      }
      
      // 复制解析图片
      if (question.explanationImageUrl != null && question.explanationImageUrl.isNotEmpty) {
        final relativePath = await copyImageToBackupDir(question.explanationImageUrl, backupDir);
        if (relativePath.isNotEmpty) {
          question.explanationImageUrl = relativePath;
        }
      }
    }
    
    // 处理笔记图片
    for (var note in notes) {
      if (note.imageUrl != null && note.imageUrl.isNotEmpty) {
        final relativePath = await copyImageToBackupDir(note.imageUrl, backupDir);
        if (relativePath.isNotEmpty) {
          note.imageUrl = relativePath;
        }
      }
    }
    
    // 处理作文素材图片
    for (var material in essayMaterials) {
      if (material.imageUrl != null && material.imageUrl.isNotEmpty) {
        final relativePath = await copyImageToBackupDir(material.imageUrl, backupDir);
        if (relativePath.isNotEmpty) {
          material.imageUrl = relativePath;
        }
      }
    }
  }
  
  /// 从备份目录恢复所有图片
  /// 
  /// [questions] 题目列表
  /// [notes] 笔记列表
  /// [essayMaterials] 作文素材列表
  /// [backupDir] 备份目录
  /// [appDir] 应用目录
  static Future<void> restoreAllImagesFromBackup(List<dynamic> questions, List<dynamic> notes, List<dynamic> essayMaterials, String backupDir, String appDir) async {
    // 处理题目图片
    for (var question in questions) {
      // 恢复题目图片
      if (question.questionImageUrl != null && question.questionImageUrl.isNotEmpty && !question.questionImageUrl.startsWith('http')) {
        final absolutePath = await copyImageFromBackupDir(question.questionImageUrl, backupDir, appDir);
        if (absolutePath.isNotEmpty) {
          question.questionImageUrl = absolutePath;
        }
      }
      
      // 恢复选项A图片
      if (question.optionAImageUrl != null && question.optionAImageUrl.isNotEmpty && !question.optionAImageUrl.startsWith('http')) {
        final absolutePath = await copyImageFromBackupDir(question.optionAImageUrl, backupDir, appDir);
        if (absolutePath.isNotEmpty) {
          question.optionAImageUrl = absolutePath;
        }
      }
      
      // 恢复选项B图片
      if (question.optionBImageUrl != null && question.optionBImageUrl.isNotEmpty && !question.optionBImageUrl.startsWith('http')) {
        final absolutePath = await copyImageFromBackupDir(question.optionBImageUrl, backupDir, appDir);
        if (absolutePath.isNotEmpty) {
          question.optionBImageUrl = absolutePath;
        }
      }
      
      // 恢复选项C图片
      if (question.optionCImageUrl != null && question.optionCImageUrl.isNotEmpty && !question.optionCImageUrl.startsWith('http')) {
        final absolutePath = await copyImageFromBackupDir(question.optionCImageUrl, backupDir, appDir);
        if (absolutePath.isNotEmpty) {
          question.optionCImageUrl = absolutePath;
        }
      }
      
      // 恢复选项D图片
      if (question.optionDImageUrl != null && question.optionDImageUrl.isNotEmpty && !question.optionDImageUrl.startsWith('http')) {
        final absolutePath = await copyImageFromBackupDir(question.optionDImageUrl, backupDir, appDir);
        if (absolutePath.isNotEmpty) {
          question.optionDImageUrl = absolutePath;
        }
      }
      
      // 恢复解析图片
      if (question.explanationImageUrl != null && question.explanationImageUrl.isNotEmpty && !question.explanationImageUrl.startsWith('http')) {
        final absolutePath = await copyImageFromBackupDir(question.explanationImageUrl, backupDir, appDir);
        if (absolutePath.isNotEmpty) {
          question.explanationImageUrl = absolutePath;
        }
      }
    }
    
    // 处理笔记图片
    for (var note in notes) {
      if (note.imageUrl != null && note.imageUrl.isNotEmpty && !note.imageUrl.startsWith('http')) {
        final absolutePath = await copyImageFromBackupDir(note.imageUrl, backupDir, appDir);
        if (absolutePath.isNotEmpty) {
          note.imageUrl = absolutePath;
        }
      }
    }
    
    // 处理作文素材图片
    for (var material in essayMaterials) {
      if (material.imageUrl != null && material.imageUrl.isNotEmpty && !material.imageUrl.startsWith('http')) {
        final absolutePath = await copyImageFromBackupDir(material.imageUrl, backupDir, appDir);
        if (absolutePath.isNotEmpty) {
          material.imageUrl = absolutePath;
        }
      }
    }
  }
}